/**************************************************************
  > File Name: mydate.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年01月02日 星期日 13时26分13秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>

/*
 *-y:year
 *-m:month
 *-d:day
 *-H:hour
 *-M:minute
 *-S:second
 */

#define BUFSIZE 1024
#define FORMATSIZE 1024
#define FLSIZE 12

int main(int argc,char **argv)
{
	FILE *fp[FLSIZE] = {NULL};
	
	int count = 0;
	int i;
	int opt = 0;
	int flag = 1;
	time_t tm;
	struct tm *tmmsg = NULL;
	char strbuf[BUFSIZE] = {0};
	char format[FORMATSIZE] = {0};

	tm = time(NULL);
	tmmsg = localtime(&tm);

	while ((opt = getopt(argc,argv,"-H:MSy:md")) != -1)
	{
		switch (opt)
		{
			case 1:	
				fp[count++] = fopen(argv[optind-1],"w+");
				if (fp[count-1] == NULL)
				{
					perror("fopen()");
					exit(1);
				}
				break;
			case 'H':
				if (strcmp(optarg,"12") == 0)
					strncat(format,"%I(%P) ",FORMATSIZE-1);
				else if (strcmp(optarg,"24") == 0)
						strncat(format,"%H ",FORMATSIZE-1);	
						else
							fprintf(stderr,"Invalid argument!\n");
				break;
			case 'M':
				strncat(format,"%M ",FORMATSIZE-1);
				break;
			case 'S':
				strncat(format,"%S ",FORMATSIZE-1);
				break;
			case 'y':
				if (strcmp(optarg,"2") == 0)
					strncat(format,"%y ",FORMATSIZE-1);
				else if (strcmp(optarg,"4") == 0)
						strncat(format,"%Y ",FORMATSIZE-1);
						else
							fprintf(stderr,"Invalid argument!\n");
				break;
			case 'm':
				strncat(format,"%m ",FORMATSIZE-1);
				break;
			case 'd':
				strncat(format,"%d ",FORMATSIZE-1);
				break;
			default:
				break;
		}
		flag = 0;
	}
	if (flag == 1)
	{
		strncat(format,"%Y-%m-%d",FORMATSIZE-1);
	}
	if (count == 0)
	{
		fp[0] = stdout;
	}


	strncat(format,"\n",FORMATSIZE-1);
	strftime(strbuf,BUFSIZE,format,tmmsg);
	for (i = 0; i < FLSIZE; i++)
	{
		if (fp[i] != NULL)
			fputs(strbuf,fp[i]);
	}
	
	for (i = 0;i < FLSIZE; i++)
		if (fp[i] != NULL && fp[i] != stdout)
			fclose(fp[i]);

    exit(0);
}
